package com.lifeverse.entity;

import com.lifeverse.entity.enums.RulePriority;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDateTime;

/**
 * 规则实体类
 * 定义决策引擎使用的规则
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "rules", indexes = {
    @Index(name = "idx_rule_name", columnList = "name"),
    @Index(name = "idx_rule_category", columnList = "category"),
    @Index(name = "idx_rule_priority", columnList = "priority"),
    @Index(name = "idx_rule_enabled", columnList = "enabled")
})
public class Rule extends BaseEntity {
    
    /**
     * 规则名称
     */
    @Column(name = "name", nullable = false, length = 100, unique = true)
    private String name;
    
    /**
     * 规则描述
     */
    @Column(name = "description", length = 500)
    private String description;
    
    /**
     * 规则分类
     */
    @Column(name = "category", nullable = false, length = 50)
    private String category;
    
    /**
     * 规则优先级
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "priority", nullable = false, length = 20)
    private RulePriority priority = RulePriority.NORMAL;
    
    /**
     * 规则条件（JSON格式或表达式）
     */
    @Column(name = "conditions", nullable = false, columnDefinition = "TEXT")
    private String conditions;
    
    /**
     * 规则动作（JSON格式或表达式）
     */
    @Column(name = "actions", nullable = false, columnDefinition = "TEXT")
    private String actions;
    
    /**
     * 是否启用
     */
    @Column(name = "enabled", nullable = false)
    private Boolean enabled = true;
    
    /**
     * 规则版本
     */
    @Column(name = "rule_version", nullable = false, length = 20)
    private String ruleVersion = "1.0";
    
    /**
     * 规则作者
     */
    @Column(name = "author", length = 100)
    private String author;
    
    /**
     * 规则标签（JSON格式）
     */
    @Column(name = "tags", length = 500)
    private String tags;
    
    /**
     * 执行次数
     */
    @Column(name = "execution_count", nullable = false)
    private Long executionCount = 0L;
    
    /**
     * 成功次数
     */
    @Column(name = "success_count", nullable = false)
    private Long successCount = 0L;
    
    /**
     * 最后执行时间
     */
    @Column(name = "last_executed_at")
    private LocalDateTime lastExecutedAt;
    
    /**
     * 最后成功时间
     */
    @Column(name = "last_success_at")
    private LocalDateTime lastSuccessAt;
    
    /**
     * 规则配置（JSON格式）
     */
    @Column(name = "configuration", columnDefinition = "TEXT")
    private String configuration;
    
    /**
     * 有效期开始时间
     */
    @Column(name = "valid_from")
    private LocalDateTime validFrom;
    
    /**
     * 有效期结束时间
     */
    @Column(name = "valid_until")
    private LocalDateTime validUntil;
    
    /**
     * 记录规则执行
     */
    public void recordExecution(boolean success) {
        this.executionCount++;
        this.lastExecutedAt = LocalDateTime.now();
        
        if (success) {
            this.successCount++;
            this.lastSuccessAt = LocalDateTime.now();
        }
    }
    
    /**
     * 计算成功率
     */
    public double getSuccessRate() {
        if (executionCount == 0) {
            return 0.0;
        }
        return (double) successCount / executionCount;
    }
    
    /**
     * 判断规则是否有效
     */
    public boolean isValid() {
        if (!enabled) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        if (validFrom != null && now.isBefore(validFrom)) {
            return false;
        }
        
        if (validUntil != null && now.isAfter(validUntil)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 判断是否为高优先级规则
     */
    public boolean isHighPriority() {
        return priority.isHigherThan(RulePriority.NORMAL);
    }
    
    /**
     * 创建规则
     */
    public static Rule create(String name, String description, String category, 
                            RulePriority priority, String conditions, String actions) {
        Rule rule = new Rule();
        rule.setName(name);
        rule.setDescription(description);
        rule.setCategory(category);
        rule.setPriority(priority);
        rule.setConditions(conditions);
        rule.setActions(actions);
        rule.setEnabled(true);
        return rule;
    }
}